# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2e7e0bb5d663966e434ca321db98b0a1': {
        #  恒捷支付 支付宝2.5%，微信2.8% 支付宝100-5000元，微信200-5000元。 witch
        'API_KEY': '4c8156749d1ab2c7b21cf02203a36928',
        'gateway': 'http://156.236.99.40:7001/createOrder',
        'query_gateway': 'http://156.236.99.40:7001/queryOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_service_id(mch_id):
    return APP_CONF[mch_id]['service_id']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_order_sign(d, key):
    s = d['order_id'] + d['order_type'] + d['order_price'] + d['redirect_url']
    s_final = _gen_sign(s) + key
    return _gen_sign(s_final)


def generate_notify_sign(d, key):
    s = d['order_id']
    s_final = _gen_sign(s) + key
    return _gen_sign(s_final)


def generate_query_sign(d, key):
    s = d['order_id'] + d['business_id']
    s_final = _gen_sign(s) + key
    return _gen_sign(s_final)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("hengjiepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型	pay_type 	 
# 微信-扫码	1000 	 
# 微信-wap	1001
# 微信-app	1002
# 支付宝-当面付	2000
# 支付宝-WAP	2001
# 支付宝-转账	2002
# 网银	5000
# 快捷	5001
# 银联扫码	5002
def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    elif service == 'wechat':
        return 'wechat'
    return 'alipay'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('business_id', app_id),
        ('order_price', str(int(pay_amount))),
        ('order_id', str(pay.id)),
        ('redirect_url', '{}/pay/api/{}/hengjiepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('order_type', _get_pay_type(service)),
        ('order_name', 'HengjieCharge'),
        ('extension', 'charge'),
    ))
    parameter_dict['sign'] = generate_order_sign(parameter_dict, api_key)
    _LOGGER.info("hengjiepay create: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['order_id'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("hengjiepay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)['data']
    return {'charge_info': data['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("hengjiepay notify data: %s, order_id is: %s", data, data['order_id'])
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('hengjiepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderStatus'])
    trade_no = ''
    total_fee = float(data['qr_price'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,00-交易成功
    if trade_status == 'SUCCESS':
        _LOGGER.info('hengjiepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('order_id', str(pay_id)),
        ('business_id', app_id),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("hengjiepay query data: %s, order_id: %s", json.dumps(parameter_dict),
                 parameter_dict['order_id'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("hengjiepay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['pay_status'])
        trade_no = ''
        total_fee = float(data['qr_price'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == u'已支付':
            _LOGGER.info('hengjiepay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('hengjiepay data error, status_code: %s', response.status_code)
